/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.psc.helpers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author A7med
 */
public class DBUtils implements Serializable{

    Connection con;
    Statement st;
    ResultSet res;
    ResultSetMetaData resMetaData;
    String sql;
    String sqlString;
    private int BUFFER = 99999;
    DBOption inst = DBOption.INTANCE;

    public String setOpenCon() {
        String ErrorMessage = "";

        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(inst.getDBURL(), inst.getDBUSER(), inst.getDBPASSWORD());
        } catch (SQLException ex) {
            ErrorMessage += ex.getMessage();
            Logger.getLogger(DBUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            ErrorMessage += ex.getMessage();
        }
        return ErrorMessage;
    }

    public String getMysqlBinPath() {
        setOpenCon();
        try {
            st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

        } catch (Exception e) {

            System.out.print("I am here yaaar");
            e.printStackTrace();
        }

        String a = "";

        try {
            res = st.executeQuery("select @@basedir");
            while (res.next()) {
                a = res.getString(1);
            }
        } catch (Exception eee) {
            eee.printStackTrace();
        }
        a = a + "/bin/";
        System.err.println("Mysql path is :" + a);
        return a;

    }

    public String backupDB(String path) {
        String Mysqlpath = getMysqlBinPath().replace("\\", "/");

        try {

            st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

        } catch (Exception e) {

            System.out.print("I am here yaaar");
            e.printStackTrace();
        }

        System.out.println(Mysqlpath);
        Process run = null;
        try {
            //"mysqldump -u" + inst.getDBUSER() + " -p" + inst.getDBPASSWORD() + " --database " + inst.getDBNAME() + " -r " + path;
            //Mysqlpath + "mysqldump --host=" + inst.getDBHOST() + " --port=" + inst.getDBPORT() + " --user=" + inst.getDBUSER() + " --password=" + inst.getDBPASSWORD() + "  " + "--skip-comments --skip-triggers -r "+path+" --database" + inst.getDBNAME()
            run = Runtime.getRuntime().exec(Mysqlpath + "mysqldump -u" + inst.getDBUSER() + " -p" + inst.getDBPASSWORD() + " --database " + inst.getDBNAME() + " -r " + path);
        } catch (IOException ex) {
            System.err.println("io error=" + ex.getLocalizedMessage());
        }

        InputStream in = run.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        StringBuffer temp = new StringBuffer();

        int count;
        char[] cbuf = new char[BUFFER];

        try {

            while ((count = br.read(cbuf, 0, BUFFER)) != -1) {
                temp.append(cbuf, 0, count);
            }
        } catch (IOException ex) {
            // Logger.getLogger(this.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {

            br.close();
            in.close();
        } catch (IOException ex) {
            //  Logger.getLogger(this.class.getName()).log(Level.SEVERE, null, ex);
        }
        return temp.toString();
    }

    public boolean restoreDB(String source) {

        String Mysqlpath = getMysqlBinPath().replace("\\", "/");
        String[] executeCmd = new String[]{Mysqlpath +"mysql", "--user=" + inst.getDBUSER(), "--password=" + inst.getDBPASSWORD(), "-e", "source " + source};

        Process runtimeProcess;
        try {

            runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();

            if (processComplete == 0) {
                System.out.println("Backup restored successfully");
                return true;
            } else {
                System.out.println("Could not restore the backup");
            }
        } catch (IOException | InterruptedException ex) {
            System.out.println("error="+ex.getLocalizedMessage());
        }

        return false;
    }

}
